# encoding=utf-8
"""
@author: xiao nian
@contact: xiaonian030@163.com
@time: 2021-12-21 15:15
"""
from deepface import DeepFace
from deepface.detectors import FaceDetector
from utils.response import api_response
from fastapi import FastAPI, Form
from config.config import HTTP_CONFIG, MODEL_CONFIG
import uvicorn
import os

app = FastAPI()

os.environ['DEEPFACE_HOME'] = MODEL_CONFIG['deepface_home']
# actions_analyze = ('emotion', 'age', 'gender', 'race')
actions_analyze = ('emotion',)
models_analyze = dict()
models_analyze['emotion'] = DeepFace.build_model('Emotion')
# models_analyze['age'] = DeepFace.build_model('Age')
# models_analyze['gender'] = DeepFace.build_model('Gender')
# models_analyze['race'] = DeepFace.build_model('Race')
# model_verify = DeepFace.build_model('VGG-Face')
detector_backend = 'mtcnn'
face_detector = FaceDetector.build_model(detector_backend)
model_verify = ''


@app.post("/detect")
def detect(image_base64: str = Form(...), test: str = Form("")):
    """
    anger: '愤怒',
    disgust: '厌恶',
    fear: '恐惧',
    happiness: '高兴',
    neutral: '平静',
    sadness: '伤心',
    surprise: '惊讶',
    """
    obj = {
        "request_id": "",
        "time_used": 0,
        "faces": [
            {
                "face_token": "",
                "face_rectangle": {
                    "top": 0,
                    "left": 0,
                    "width": 0,
                    "height": 0
                },
                "attributes": {
                    "emotion": {
                        "anger": 0,
                        "disgust": 0,
                        "fear": 0,
                        "happiness": 0,
                        "neutral": 0,
                        "sadness": 0,
                        "surprise": 0
                    },
                }
            }
        ],
        "image_id": "",
        "face_num": 1
    }
    try:
        obj_req = DeepFace.analyze(img_path=image_base64,
                                   actions=actions_analyze,
                                   models=models_analyze,
                                   enforce_detection=False,
                                   face_detector=face_detector,
                                   detector_backend=detector_backend)
        obj["faces"][0]["face_rectangle"] = obj_req["face_rectangle"]
        obj["faces"][0]["attributes"]["emotion"] = obj_req["emotion"]
        return obj
    except:
        return obj


@app.post("/verify")
def verify(image1_base64: str = Form(...), image2_base64: str = Form(...)):
    obj = {
        "verified": False,
        "distance": 0,
        "max_threshold_to_verify": 0,
        "model": "VGG-Face",
        "similarity_metric": "cosine"
    }
    try:
        obj = DeepFace.verify(img1_path=image1_base64,
                              img2_path=image2_base64,
                              model_name='VGG-Face',
                              distance_metric='cosine',
                              model=model_verify)
        return api_response(0, obj, 'OK')
    except:
        return api_response(400, obj, 'error')


if __name__ == '__main__':
    print('启动程序')
    uvicorn.run(
        app='run_http:app',
        host=HTTP_CONFIG['host'],
        port=HTTP_CONFIG['port'],
        workers=HTTP_CONFIG['workers'],
        reload=False,
        debug=False,
        access_log=False,
        log_level='error')
